import React, { FC, useState } from 'react'
import {
  Button,
  Checkbox,
  Col,
  Form,
  Input,
  InputNumber,
  DatePicker,
  Radio,
  Row,
  Select,
  message,
  Upload,
  Modal,
} from 'antd'
import {
  UploadOutlined,
  LoadingOutlined,
  PlusOutlined,
} from '@ant-design/icons'
import type { DatePickerProps } from 'antd'
import type { UploadChangeParam } from 'antd/es/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { ProjectAddress } from '../index.d'
import moment, { Moment } from 'moment'
import { dataFormat1 } from '@/untils/dictionaries'
import { connect } from 'umi'

const { Option } = Select
const { RangePicker } = DatePicker
const { TextArea } = Input
const { Item } = Form

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
}

interface IProps {
  InnerEditTable: {
    total: number
    isModalVisible: boolean
  }
  dispatch: FC
}
const AddModel = (props: IProps) => {
  console.log('执行弹窗')

  const {
    InnerEditTable: { total, isModalVisible },
    dispatch,
  } = props

  const [form] = Form.useForm()
  const [projectRegion, setProjectRegion] = useState<ProjectAddress[]>([
    { value: '1', label: '地区1' },
  ]) //项目地区列表
  const [projectPrincipal, setProjectPrincipal] = useState<ProjectAddress[]>([
    { value: '1', label: '负责人1' },
  ]) //项目负责人列表
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>()
  const [serviceContentList, setServiceContentList] = useState<
    ProjectAddress[]
  >([
    { value: '1', label: '产品规划' },
    { value: '2', label: 'UI设计' },
    { value: '3', label: '技术开发' },
    { value: '4', label: '测试上线' },
  ])
  const [serviceTypeList, setServiceTypeList] = useState<ProjectAddress[]>([
    { value: '1', label: '离岸开发' },
    { value: '2', label: '人员服务' },
    { value: '3', label: '第三方外包' },
  ]) //服务类型列表

  const [projectPeriod, setProjectPeriod] = useState<Moment[]>([
    moment('1999-1-1'),
    moment('1999-1-1'),
  ]) //项目周期开始时间  同步
  const handleOk = () => {
    form.validateFields().then(res => {
      //验证通过
      console.log(1, res)
      res.key = total + 1
      dispatch({
        type: 'InnerEditTable/addTableData',
        payload: res,
      })
      dispatch({
        type: 'InnerEditTable/setIsModalVisible',
        payload: false,
      })
    })
  }

  const handleCancel = () => {
    dispatch({
      type: 'InnerEditTable/setIsModalVisible',
      payload: false,
    })
  }

  const onFinish = (values: any) => {
    console.log('Received values of form: ', values)
  }

  const handleDataChange: DatePickerProps['onChange'] = date => {
    //moment
    date ? setProjectPeriod([date]) : setProjectPeriod([])

    form.setFieldsValue({ projectStartTime: date })
  }
  const handleDataListChange: DatePickerProps['onChange'] = date => {
    //[moment,moment]
    date ? setProjectPeriod(date) : setProjectPeriod([])

    console.log('handleDataListChange', date)
  }
  //上传图片
  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, url => {
        setLoading(false)
        setImageUrl(url)
      })
    }
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  )
  return (
    <Modal
      title="新建项目"
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      okText="确定"
      cancelText="取消"
      destroyOnClose
    >
      <Form
        form={form}
        name="validate_other"
        {...formItemLayout}
        onFinish={onFinish}
        initialValues={{
          'input-number': 3,
          'checkbox-group': ['A', 'B'],
          rate: 3.5,
        }}
      >
        <Item name="projectID" label="项目编号" rules={[{ required: true }]}>
          <Input placeholder="请输入项目编号" />
        </Item>
        <Item name="projectName" label="项目名称" rules={[{ required: true }]}>
          <Input placeholder="请输入项目名称" />
        </Item>
        <Item
          name="region"
          label="项目地区"
          hasFeedback
          rules={[{ required: true }]}
        >
          <Select placeholder="请选择项目所在地">
            {projectRegion.map((item: ProjectAddress) => (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Item>
        <Item
          name="projectAddress"
          label="项目地址"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入项目地址"></Input>
        </Item>
        <Item
          name="projectPrincipal"
          label="项目负责人"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Select placeholder="请选择项目负责人">
            {projectPrincipal.map((item: ProjectAddress) => (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Item>
        <Item
          label="项目开始时间"
          name="projectStartTime"
          rules={[{ required: true }]}
        >
          <DatePicker
            onChange={handleDataChange}
            showTime
            showToday
            placeholder="请选择开始时间"
          />
          ;
        </Item>
        <Item label="项目周期">
          <RangePicker
            value={projectPeriod}
            format={dataFormat1}
            onChange={handleDataListChange}
          />
        </Item>
        <Item label="项目图" valuePropName="fileList">
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </Item>
        <Item name="projectMoney" label="项目金额">
          <InputNumber addonBefore="¥" step={100} />
        </Item>
        <Item name="projectDesc" label="项目描述">
          <TextArea rows={4} placeholder="请输入项目描述" />
        </Item>
        <Item
          name="serviceContent"
          label="服务内容"
          rules={[{ required: true }]}
        >
          <Checkbox.Group>
            <Row>
              {serviceContentList.map((item: ProjectAddress) => (
                <Col span={8} key={item.value}>
                  <Checkbox value={item.value} style={{ lineHeight: '32px' }}>
                    {item.label}
                  </Checkbox>
                </Col>
              ))}
            </Row>
          </Checkbox.Group>
        </Item>
        <Item name="serviceType" label="服务类型" rules={[{ required: true }]}>
          <Radio.Group>
            {serviceTypeList.map(item => (
              <Radio value={item.value} key={item.value}>
                {item.label}
              </Radio>
            ))}
          </Radio.Group>
        </Item>
        <Item
          name="upload"
          label="附件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          extra="上传文件最多上传3份附件,单个附件不大于50MB,支持扩展名：.rar .zip .doc .docx .pdf .jpg..."
        >
          <Upload name="logo" action="/upload.do" listType="picture">
            <Button icon={<UploadOutlined />}>上传文件</Button>
          </Upload>
        </Item>
      </Form>
    </Modal>
  )
}

export default connect(({ InnerEditTable }: any) => ({ InnerEditTable }))(
  AddModel,
)
const normFile = (e: any) => {
  console.log('Upload event:', e)
  if (Array.isArray(e)) {
    return e
  }
  return e?.fileList
}
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!')
  }
  return isJpgOrPng && isLt2M
}
